package com.phiture.erp.produce.web.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialUnitResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.basic.api.service.ErpMaterialUnitApi;
import com.phiture.erp.common.constants.DictTypeConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.enums.ErpProductionTaskStatusEnum;
import com.phiture.erp.produce.core.pojo.vo.*;
import com.phiture.erp.produce.core.service.ErpProduceInService;
import com.phiture.erp.produce.dal.entity.ErpBomItemsDO;
import com.phiture.erp.produce.dal.entity.ErpProduceInDO;
import com.phiture.erp.produce.dal.entity.ErpProduceInItemsDO;
import com.phiture.erp.produce.dal.entity.ErpProduceProcessDO;
import com.phiture.erp.produce.dal.pojo.vo.ErpProduceInRespVO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - 生产入库-包含成品，半成品")
@RestController
@RequestMapping("/erp/produce-in")
@Validated
public class ErpProduceInController {

    @Resource
    private ErpProduceInService produceInService;

    @Resource
    private ErpMaterialApi erpMaterialApi;

    @Resource
    private ErpMaterialUnitApi erpMaterialUnitApi;

    @Resource
    private DictDataService dictDataService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建生产入库-包含成品，半成品")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:create')")
    public CommonResult<Long> createProduceIn(@Valid @RequestBody ErpProduceInSaveReqVO createReqVO) {
        return success(produceInService.createProduceIn(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产入库-包含成品，半成品")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:update')")
    public CommonResult<Boolean> updateProduceIn(@Valid @RequestBody ErpProduceInSaveReqVO updateReqVO) {
        produceInService.updateProduceIn(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新生产入库单的状态")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:update-status')")
    public CommonResult<Boolean> updatePurchaseOrderStatus(@RequestParam("id") Long id,
                                                           @RequestParam("status") Integer status,
                                                           @RequestParam(value = "warehouseId", required = false) Long warehouseId,
                                                           @RequestParam(value = "finalQty", required = false) BigDecimal finalQty)  {
        produceInService.updateProduceInStatus(id, status,warehouseId, finalQty);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产入库-包含成品，半成品")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:produce-in:delete')")
    public CommonResult<Boolean> deleteProduceIn(@RequestParam("id") Long id) {
        produceInService.deleteProduceIn(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产入库-包含成品，半成品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:query')")
    public CommonResult<ErpProduceInRespVO> getProduceIn(@RequestParam("id") Long id) {
        ErpProduceInDO produceIn = produceInService.getProduceIn(id);
        return success(BeanUtils.toBean(produceIn, ErpProduceInRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产入库-包含成品，半成品分页")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:query')")
    public CommonResult<PageResult<ErpProduceInRespVO>> getProduceInPage(@Valid ErpProduceInPageReqVO pageReqVO) {
        PageResult<ErpProduceInRespVO> pageResult = produceInService.getProduceInPage(pageReqVO);

        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(pageResult.getList(), ErpProduceInRespVO::getMaterialId));

        // 根据申请单中的申请人ID批量查出申请人姓名
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), produceIn -> produceIn.getCreatorId()));

        for (ErpProduceInRespVO produceIn : pageResult.getList()) {
            // 物料名称
            MapUtils.findAndThen(materialMap, produceIn.getMaterialId(), material -> produceIn.setMaterialName(material.getName())
                    .setMaterialNumber(material.getBarCode())
                    .setModel(material.getStandard())
                    .setUnitName(material.getUnitName()));
            // 申请人姓名
            MapUtils.findAndThen(userMap, produceIn.getCreatorId(), user -> produceIn.setCreatorName(user.getNickname()));

            produceIn.setStatusName(ErpAuditStatus.fromStatus(produceIn.getStatus()).getName());

        }
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产入库-包含成品，半成品 Excel")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProduceInExcel(@Valid ErpProduceInPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpProduceInRespVO> list = produceInService.getProduceInPage(pageReqVO).getList();

        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(list, ErpProduceInRespVO::getMaterialId));

        // 根据申请单中的申请人ID批量查出申请人姓名
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(list, produceIn -> produceIn.getCreatorId()));

        for (ErpProduceInRespVO produceIn : list) {
            // 物料名称
            MapUtils.findAndThen(materialMap, produceIn.getMaterialId(), material -> produceIn.setMaterialName(material.getName())
                    .setMaterialNumber(material.getBarCode())
                    .setModel(material.getStandard())
                    .setUnitName(material.getUnitName()));
            // 申请人姓名
            MapUtils.findAndThen(userMap, produceIn.getCreatorId(), user -> produceIn.setCreatorName(user.getNickname()));

        }
        // 导出 Excel
        ExcelUtils.write(response, "生产入库-包含成品，半成品.xls", "数据", ErpProduceInRespVO.class,
                        BeanUtils.toBean(list, ErpProduceInRespVO.class));
    }

    // ==================== 子表（生产入库明细） ====================

    @GetMapping("/produce-in-items/list-by-produce-in-id")
    @Operation(summary = "获得生产入库明细列表")
    @Parameter(name = "produceInId", description = "生产入库ID")
    @PreAuthorize("@ss.hasPermission('erp:produce-in:query')")
    public CommonResult<List<ErpProduceInItemsRespVO>> getProduceInItemsListByProduceInId(@RequestParam("produceInId") Long produceInId) {
        return success(buildErpProduceInItemsRespVo(produceInService.getProduceInItemsListByProduceInId(produceInId)));
    }
    private List<ErpProduceInItemsRespVO> buildErpProduceInItemsRespVo(List<ErpProduceInItemsDO> result) {
        if (CollUtil.isEmpty(result)) {
            return Collections.emptyList();
        }
        // 物料信息
        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(result, ErpProduceInItemsDO::getMaterialId));
        // 基本状态
        List<DictDataDO> list =
                dictDataService.getDictDataList(CommonStatusEnum.ENABLE.getStatus(), DictTypeConstants.ERP_BILL_STATUS);
        Map<Integer, DictDataDO> billStatusrMap =  convertMap(list, DictDataDO::getValueInteger);

        List<ErpProduceInItemsRespVO> resultResp =  BeanUtils.toBean(result, ErpProduceInItemsRespVO.class, erpProduceInItemsRespVO ->{
            MapUtils.findAndThen(materialMap, erpProduceInItemsRespVO.getMaterialId(), material -> erpProduceInItemsRespVO.setMaterialNumber(material.getBarCode()).setMaterialName(material.getName())
                    .setModel(material.getStandard()));
        });
        return resultResp;
    }

}